﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace KCommon
{
    public class JsonHandler
    {
        public static string ConvertToJsonString<T>(T t)
        {
            try
            {
                string jsonString = "";
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream();
                js.WriteObject(ms, t);
                ms.Position = 0;
                StreamReader sr = new StreamReader(ms, Encoding.UTF8);
                jsonString = sr.ReadToEnd();
                sr.Close();
                ms.Close();
                return jsonString;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }           
        }

        public static T ConvertToJsonObject<T>(string jsonString)
        {
            try
            {
                if (string.IsNullOrEmpty(jsonString))
                {
                    return default(T);
                }
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(T));
                    T model = (T)deseralizer.ReadObject(ms);
                    return model;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }          
        }    

    }
}
